<?php


namespace App\HttpController\Admin;

use App\Model\FormidsModel;
use App\Model\RecordsModel;
use App\Model\TmplmsgsModel;
use App\Utility\MiniProgram;
use App\Utility\RedisTools;
use Carbon\Carbon;
use EasySwoole\EasySwoole\Logger;

class Message extends Auth {

    public function index(){
        $wechat = new MiniProgram();
        $list = $wechat->getTemplateList();
        $model = new TmplmsgsModel();
        foreach ($list as &$item){
            $content = explode('}}', $item['content']);
            $keyword = array();
            $keywordText = [];
            foreach ($content as $val) {
                $keyword[] = trim(substr($val, strpos($val, "{{") + 2, -5));
                $keywordText[] = trim(substr($val, 0, strpos($val, "{{")));
            }
            $form = [];
            //获取数据库对应关键词的值，进行填充返回
            $keywordForDB = $model->where('template_id', $item['template_id'])->first();
            if (!$keywordForDB) {
                //模板ID不存在，创建
                foreach ($keyword as $word) {
                    if ($word) {
                        $form[$word] = '';
                    }
                }
                $item['page'] = '';
                $item['emphasis'] = '';
                $createData = [
                    'template_id' => $item['template_id'],
                    'keywords' => [$form],
                    'page' => $item['page'],
                    'title' => $item['title'],
                    'emphasis' => $item['emphasis'],
                ];
                $model->create($createData);
            } else {
                $form = $keywordForDB['keywords'];
                $item['page'] = $keywordForDB['page'];
                $item['emphasis'] = $keywordForDB['emphasis'];
            }
            $item['form'] = $form;
            $item['keyword'] = array_filter($keyword);
            $item['keyword_text_arr'] = array_combine($item['keyword'], array_filter($keywordText));
            $item['keyword_text'] = implode(',', array_filter($keywordText));
        }
        //查询formid相关（总数，总可用数，今日可用数，今日新增数）
        $formModel = new FormidsModel();
        //删除已过期的
        $formModel->clear();
//        $total = $formModel->select('id')->count();
//        $todayUseTotal = $formModel->select('openid')->where('expires_at',time(),'>')
//            ->groupBy('openid')->count();
//        $todayNewTotal = $formModel->select('id')->whereDate('created_at',Carbon::now()->toDateString())->count();
        return $this->writeJson(0,[
            'list'=>$list,
            'total'=>0,
            'today_use_total'=>0,
            'today_new_total'=>0
        ]);
    }

    public function record(){
        $request = $this->request();
        $page = $request->getRequestParam('page') ?? 1;
        $model = new RecordsModel();
        $list = $model->orderBy('start_at')->paginate($page);
        return $this->writeJson(0,$list);
    }

    /**
     * 更新
     * @return bool
     * @throws \Throwable
     */
    public function update(){
        try{
            $request = $this->request();
            $data = $request->getRequestParam();
            $model = new TmplmsgsModel();
            $msg = $model->where('template_id', $data['template_id'])->first();
            if (!$data['template_id'] || !$msg) {
                return $this->writeJson(1,null,'数据不存在');
            }
            $data['id'] = $msg['id'];
            $model->update($data);
            return $this->writeJson(0, null, '更新成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }


    public function push(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $msg = (new TmplmsgsModel())->where('template_id', $data['id'])->first();
        if (!$data['id'] || !$msg) {
            return $this->writeJson(1,null,'数据不存在');
        }
        //删除无用的记录
        (new FormidsModel())->where('expires_at',time(),'<=')->delete();
        //生成推送记录
        $insert = [
            'template_id' => $data['id'],
            'title' => $msg['title'],
        ];
        (new RecordsModel())->create($insert);
        //开启任务-创建模板消息推送队列
        $queue = new RedisTools('message-openid');
        $queue->lPush($data['id']);
        return $this->writeJson(0, null, '推送成功');
    }

    public function token(){
        $wechat = new MiniProgram();
        $token = $wechat->getToken(true);
        return $this->writeJson(0, $token, '重置access_token成功');
    }
}
